package com.wolfsea.defineviewpageindicator
import android.content.Context
import android.graphics.PointF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View

/*
* 多点触摸(接力型):同一时刻只有最新的那个手指能起作用
* */
class MultiTouchView1 @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : View(context, attributeSet) {

    //按下时的坐标
    private val mDownPointF by lazy {
        PointF()
    }

    //偏移坐标
    private val mOffsetPointF by lazy {
        PointF()
    }

    //上次偏移坐标
    private val mLastOffsetPointF by lazy {
        PointF()
    }

    //当前正在监控的手指id
    private var mPointerId = 0

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        performClick()
        when (event?.actionMasked) {
            MotionEvent.ACTION_DOWN,
            MotionEvent.ACTION_POINTER_DOWN -> {
                setTrackingPointer(event.actionIndex, event)
            }
            MotionEvent.ACTION_MOVE -> {
                val actionIndex = event.findPointerIndex(mPointerId)
                mOffsetPointF.x = mLastOffsetPointF.x + event.getX(actionIndex) - mDownPointF.x
                mOffsetPointF.y = mLastOffsetPointF.y + event.getY(actionIndex) - mDownPointF.y
                invalidate()
            }
            MotionEvent.ACTION_POINTER_UP -> {
                val actionIndex = event.actionIndex
                val pointerId = event.getPointerId(actionIndex)
                //判断抬起的手指是否是当前正在监控的手指
                if (mPointerId == pointerId) {
                    //判断抬起的手指是否是最后一个,并将当前追踪点设置为最后一个index对应的pointer
                    val newIndex =
                        if (actionIndex == event.pointerCount - 1) event.pointerCount - 2 else event.pointerCount - 1
                    setTrackingPointer(newIndex, event)
                }
            }
        }
        return true
    }

    override fun performClick(): Boolean {
        return super.performClick()
    }

    /*
    * 设置当前追踪的Pointer
    * */
    private fun setTrackingPointer(newPointerIndex: Int, event: MotionEvent) {
        mPointerId = event.getPointerId(newPointerIndex)
        mDownPointF.x = event.getX(newPointerIndex)
        mDownPointF.y = event.getX(newPointerIndex)
        mLastOffsetPointF.x = mOffsetPointF.x
        mLastOffsetPointF.y = mOffsetPointF.y
    }

}